package com.qjdchina.sku.front.web.controller;

import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qjdchina.common.web.util.RestBody;
import com.qjdchina.commons.result.Result;
import com.qjdchina.sku.biz.UserManager;
import com.qjdchina.sku.biz.VerifyCodeManager;
import com.qjdchina.sku.consts.SessionKeyConsts;
import com.qjdchina.sku.enums.UserType;
import com.qjdchina.sku.model.User;
import com.qjdchina.sku.model.definition.YunpianTemplateDefinition;
import com.qjdchina.sku.model.vo.VerifyCodeVo;
import com.qjdchina.sku.service.enums.SkuResultCode;
import com.qjdchina.sku.util.DateUtil;


/**
 * 获取图像验证码、获取手机验证码、校验图片验证码、校验手机验证码、校验原密码
 * 
 * @author xue_dong
 * @date 2016年1月21日上午9:06:51
 * @version 1.0
 */
@Controller
@RequestMapping(value = "/verify")
public class VerifyCodeController {

	private static final Logger LOGGER = LoggerFactory.getLogger(VerifyCodeController.class);

	@Autowired
	private VerifyCodeManager manager;
	@Autowired
	private UserManager userManager;

	/**
	 * 获取图片验证码
	 *
	 * @param session
	 * @param response
	 */
	@RequestMapping(value = "/getImgCode", method = RequestMethod.GET)
	@ResponseBody
	public void getVerifyGgCode(HttpSession session, HttpServletResponse response) {

		try {

			// 生成验证码
			Result<VerifyCodeVo> result = manager.generateCode(4);

			session.setAttribute(SessionKeyConsts.IMG_VERIFY_CODE, result.getDataModel().getVerifyCode());
			session.setAttribute(SessionKeyConsts.IMG_DATE, result.getDataModel().getDate());

			LOGGER.debug("put code into session[{}]: {}", session.getId(), result.getDataModel().getVerifyCode());

			// 生成图片，把验证码放到图片中
			int w = 100, h = 40;
			manager.outputImage(w, h, response.getOutputStream(), result.getDataModel().getVerifyCode());

			LOGGER.debug("get code immediately from session[{}]: {}", session.getId(),
					session.getAttribute(SessionKeyConsts.IMG_VERIFY_CODE));

		} catch (Exception e) {
			LOGGER.warn("getVerify code fail... system exception. ", e);
		}
	}

	/**
	 * 校验图片验证码
	 * 
	 * @param session
	 * @param verifyCode
	 * @return
	 */
	@RequestMapping(value = "/checkImgCode", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<String> checkImgVerificationCode(HttpSession session,
			@RequestParam("verifyCode") String verifyCode) {

		// 验证码校验
		String code = (String) session.getAttribute(SessionKeyConsts.IMG_VERIFY_CODE);
		Date imgDate = (Date) session.getAttribute(SessionKeyConsts.IMG_DATE);
		// 打印SESSION ATTRIBUTES
		Enumeration<String> attributeNames = session.getAttributeNames();
		LOGGER.debug("session[{}] attributes as flow:::::", session.getId());
		while (attributeNames.hasMoreElements()) {
			String attributeName = attributeNames.nextElement();
			LOGGER.debug("attribute[{}]'s value: {}", attributeName, session.getAttribute(attributeName));
		}
		Result<String> result = manager.checkImgVerificationCode(code, verifyCode, imgDate);
		if (result.isSuccess()) {
			session.removeAttribute(SessionKeyConsts.IMG_VERIFY_CODE);
			session.removeAttribute(SessionKeyConsts.IMG_DATE);
			return new RestBody<String>(SkuResultCode.SUCCESS);
		}
		return new RestBody<String>(result.getCode(), result.getMessage());
	}

	/**
	 * 获取短信验证码
	 *
	 * @param phone
	 * @param password
	 * @param request
	 * @param httpSession
	 * @return
	 */
	@RequestMapping(value = "/fetchSmsCode", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<?> fetchSmsCode(@RequestParam("phone") String phone,
			@RequestParam(value = "password", required = false) String password, HttpServletRequest request,
			HttpSession httpSession) {

		//校验账号密码是否正确
		Result<User> resultUser = userManager.getUserByUserName(phone, password);
		if(!resultUser.isSuccess()){
			return new RestBody<String>(resultUser.getCode(),resultUser.getMessage());
		}
		User user = resultUser.getDataModel();
		String userType = user.getUserType();
		//如果登陆的账号是厂家的,提示用户名或者密码错误
		if(userType.equals(UserType.SUPPLIER.getValue())){
			return new RestBody<String>(SkuResultCode.USER_CANT_FIND);
		}


		VerifyCodeVo verifyCodeVo = (VerifyCodeVo) httpSession.getAttribute(SessionKeyConsts.VERIFY_CODE_VO);
		// 1分钟内不能重复发送短信验证
		if (verifyCodeVo != null && !DateUtil.isBefore(new Date(), verifyCodeVo.getDate(), 60)) {
			LOGGER.warn("validation code timed out");
			return new RestBody<String>(SkuResultCode.SKU_FNT_VERIFY_CODE_NOT_REPEAT_SEND);
		}

		// 以“是否含OpenId头域”判断是否来自微信客户端
		String oepnId = request.getHeader("q-open-id");
		boolean fromWechat = !StringUtils.isEmpty(oepnId);
		// 要求必须携带正确的SESSION_ID
		boolean createSession = fromWechat;
		HttpSession session = request.getSession(createSession);
		return sendSmsCode(phone, Long.parseLong(YunpianTemplateDefinition.GET_SMS_CODE_ID), session);

	}


	// 发送短信验证码
	private RestBody<String> sendSmsCode(String phone, long codeId, HttpSession session) {
		Result<VerifyCodeVo> result = manager.sendVerificationCode(phone, codeId);
		LOGGER.debug("verifyCodeController sendSmsCode result [{}]: {}", result);
		if (result.isSuccess()) {
			if (result.getDataModel() != null) {
				LOGGER.debug("verifyCodeController sendSmsCode smsCode [{}]: {}", result.getDataModel().getVerifyCode());
				session.setAttribute(SessionKeyConsts.VERIFY_CODE_VO, result.getDataModel());
				return new RestBody<String>(SkuResultCode.SUCCESS);
			}
		}
		// 1.2.2 发送失败
		return new RestBody<String>(result.getCode(), result.getMessage());
	}

}
